<?php
namespace Client\Controller;

use Zend\View\Model\ViewModel;
use Zend\View\Model\JsonModel;


class MaterialController extends InitializeController
{ 
	
	protected function getCategoryMaterials($categories){
		$categoryMaterials=array();//类目材料
		$categoryIds=array();//类目id
		$materials=array();//材料数据来自数据库
		$materialArr=array();//处理后的材料
	
		foreach($categories as $k=> $v){
			$categoryMaterials[$v['material_category_id']]['data']=$v;
			$categoryIds[]=$v['material_category_id'];
		}
		
		$materials=$this->getMaterialTable()->getCategoryMaterials($categoryIds);
		foreach($materials as $k=>$v){
			$materialArr[$v['material_category_id']][]=$v;
		}
		foreach($categoryMaterials as $k=>$v){
			
			$categoryMaterials[$k]['materials']=$materialArr[$k];
		}
		return $categoryMaterials;
	} 
	

	
    public function indexAction(){
    	$catalogs=array();
    	$categories=array();
    	$materials=array();
    	
    	$catalogList = $this->getMaterialCatalogTable()->getAll();
    	$categories= $this->getMaterialCategoryTable()->fetchAll();
    	$categoryMaterialRs=$this->getCategoryMaterials($categories);
    	
        return new ViewModel(array(
			'catalogList' => $catalogList,
			'categories' => $categories,
			'categoryMaterials' => $categoryMaterialRs
		));
    }
    
    public function detailAction(){
    	$materialDetail=array();//材料详细信息
    	$materialId=$this->params()->fromRoute("material_id","7");
    	
    	$banners=$this->getBannerTAble()->getItems(2);
    	$materialDetail=$this->getMaterialTable()->getItem($materialId);
    	$monitorReports=$this->getMonitorReportTable()->getReports($materialId);
    	$yearList=array();
    	$monthList=array();
    	$dayList=array();
    	$_date=array();
    	for($i=1;$i<=12;$i++){
    		$monthList[]=$i;
    	}
    	for($i=1;$i<=31;$i++){
    		$dayList[]=$i;
    	}
    	for($i=4;$i>=0;$i--){
    		$year=date('Y',strtotime("-{$i} year"));
    		$yearList[]=$year;
    	}
    	$_date['y']=$yearList;
    	$_date['m']=$monthList;
    	$_date['d']=$dayList;
        $view =new ViewModel(array(
			'materialDetail'=>$materialDetail,
			'monitorReports'=>$monitorReports,
			'banners'=>$banners,
			'_date'=>$_date
        ));
        $view->setTemplate('client/material/source-detail.phtml');
        return $view;
    }

    public function searchReportAction(){
    	$year=$_REQUEST['year'];
    	$month=$_REQUEST['month'];
    	$day=$_REQUEST['day'];
    	$materialId=$_REQUEST['materialId'];
    	$query=array();
    	$query['y']=$year?$year:"2016";
    	$query['m']=$month?$month:"9";
    	$query['d']=$day?$day:28;
    	$query['material_id']=$materialId?$materialId:7;
    	$monitorReports=$this->getMonitorReportTable()->searchMaterialReport($query);
    	echo json_encode($monitorReports);
    	die;
    	    	
    }
    

}